package captcha

import (
	"bytes"
	"io"
	"net/http"
	"time"
)

type Config struct {
	Key string
	Code string
	Width int
	Height int
}
func (c *Config) GetCaptcha(w http.ResponseWriter, r *http.Request) (string,error) {
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")
	var content bytes.Buffer
	w.Header().Set("Content-Type", "image/png")
	if c.Width == 0 {
		c.Width = 160
	}
	if c.Height == 0 {
		c.Height = 60
	}
	code,err := writeImage(&content, "", c )
	if err != nil {
		return "",err
	}
	http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(content.Bytes()))
	return code,nil
}

// WriteImage writes PNG-encoded image representation of the captcha with the
// given id. The image will have the given width and height.
func writeImage(w io.Writer, id string, c *Config) (string,error) {
	d :=  RandomDigits(6)
	 e := make([]byte,len(d))
	for i:=0;i<len(d);i++ {
		e[i] = d[i]+48
	}
	verifyCode := string(e[:])
	_, err := NewImage(id, d, c.Width, c.Height).WriteTo(w)
	return verifyCode,err

}

